# -*- coding: utf-8 -*-
'''
Created on 11-10-2012

@author: LONG HOANG GIANG
'''
import sqlite3 as db
import traceback
import re



class SQLiteHelper():
    
    __conn = None
    __cursor = None
    
    
    def __init__(self, database):
        self.__conn = db.connect(database)
        self.__cursor = self.__conn.cursor()
    
    def get_list_tables(self):
        self.execute("SELECT tbl_name FROM sqlite_master WHERE type='table' AND name != 'sqlite_sequence'")
        tables = self.fetchall()
        return [i[0] for i in tables]
    
    def get_list_index(self):
        self.execute("SELECT name FROM sqlite_master WHERE type='index'")
        list_index = self.fetchall()
        return [i[0] for i in list_index]
    
    def table_exists(self, table):
        tables = self.get_list_tables()
        return table in tables
    
    def get_cursor(self):
        return self.__cursor
    
    def execute(self, sql, *args):
        if sql == '': return
        arg = args[0] if len(args)>0 else None
        tname = type(arg).__name__
        if arg != None and arg != ():
            if tname != 'tuple' and tname != 'list': arg = [arg]
            self.__cursor.execute(sql, arg)
        else:
            self.__cursor.execute(sql)
        result = self.__cursor.lastrowid
        return result
    
    def executescript(self, sql):
        self.__cursor.executescript(sql)
    
    def fetchall(self):
        return self.__cursor.fetchall() if self.__cursor != None else None
    
    def fetchone(self):
        return self.__cursor.fetchone() if self.__cursor != None else None
    
    def commit(self):
        if self.__conn is not None: 
            self.__conn.commit()
    
    def close(self):
        try:
            if self.__cursor != None:
                self.__cursor.close(); self.__cursor = None
                
            if self.__conn != None:
                self.__conn.close(); self.__conn = None 
                
        except:
            traceback.print_exc()
        return
    
    
    def __del__(self):
        self.close()
    
     